package erz.printing.police.notch;

import android.graphics.Rect;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.view.DisplayCutout;
import android.view.View;
import android.view.Window;
import android.view.WindowInsets;
import android.view.WindowManager;

import java.util.ArrayList;
import java.util.List;

class PNotchScreenSupport implements INotchScreenSupport {
    @RequiresApi(api = Build.VERSION_CODES.P)
    @Override
    public boolean hasNotchInScreen(Window window) {
        View decorView = window.getDecorView();
        WindowInsets windowInsets = decorView.getRootWindowInsets();
        if (windowInsets == null) {
            return false;
        }
        DisplayCutout dct = windowInsets.getDisplayCutout();
        return dct != null && (dct.getSafeInsetTop() != 0
            || dct.getSafeInsetBottom() != 0
            || dct.getSafeInsetLeft() != 0
            || dct.getSafeInsetRight() != 0);
    }

    @RequiresApi(api = Build.VERSION_CODES.P)
    @Override
    public List<Rect> getNotchSize(Window window) {
        ArrayList<Rect> result = new ArrayList<>();
        View decorView = window.getDecorView();
        WindowInsets windowInsets = decorView.getRootWindowInsets();
        if (windowInsets == null) {
            return result;
        }
        DisplayCutout dct = windowInsets.getDisplayCutout();
        if (dct != null) {
            result.addAll(dct.getBoundingRects());
        }
        return result;
    }

    @RequiresApi(api = Build.VERSION_CODES.P)
    @Override
    public void setWindowLayoutAroundNotch(Window window) {
        WindowManager.LayoutParams attributes = window.getAttributes();
        attributes.layoutInDisplayCutoutMode = WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES;
        window.setAttributes(attributes);
    }

    @RequiresApi(api = Build.VERSION_CODES.P)
    @Override
    public void setWindowLayoutBlockNotch(Window window) {
        WindowManager.LayoutParams attributes = window.getAttributes();
        attributes.layoutInDisplayCutoutMode = WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_NEVER;
        window.setAttributes(attributes);
    }
}
